package branch.feature.googlemap_api_learn.ch5;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.mynewsapp.R;

// 跳转谷歌地图，
public class MainActivity extends AppCompatActivity {

    private EditText edFromLocation;
    private EditText edToLocation;
    private Button btCheck;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_ch5);


        edFromLocation = findViewById(R.id.edFrom);
        edToLocation = findViewById(R.id.edTo);
        btCheck = findViewById(R.id.btCheck);


        btCheck.setOnClickListener(view -> {
            String userLocation = edFromLocation.getText().toString();
            String userDestination = edToLocation.getText().toString();

            if (userDestination.equals("") || userDestination.equals("")) {
                Toast.makeText(this, "fill the text", Toast.LENGTH_SHORT).show();
            } else {
                getDirection(userLocation, userDestination);
            }

        });


    }

    private void getDirection(String userLocation, String userDestination) {
        try {
            // 跳转到谷歌地图
            Uri uri = Uri.parse("https://www.google.com/maps/dir/" + userLocation + "/"
                    + userDestination);

            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage("com.google.android.apps.maps");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }
}
